<template>
  <div class="caller">
    <div class="videos">
      <video controls="controls" ref="video1" class="video" />
      <video controls="controls" ref="video" class="video" />
    </div>
  </div>
</template>
<script>
import { getUserMediaSource, createPeerConnection } from '../function.js';
import { from, merge } from 'rxjs';
import { filter, tap, map, switchMap } from 'rxjs/operators';
export default {
  props: ['subject'],
  created() {
    const next = params => {
      this.subject.next({ ins: this, params });
    };
    const source = this.subject.pipe(filter(val => val.ins !== this));
    getUserMediaSource({ video: true })
      .pipe(
        switchMap(stream => {
          const video = this.$refs.video;
          video.srcObject = stream;
          video.play();
          const peerConnection = createPeerConnection();
          peerConnection.addStream(stream);
          return peerConnection.negotiationneededSource.pipe(
            switchMap(() => from(peerConnection.createOffer())),
            switchMap(offer => from(peerConnection.setLocalDescription(offer))),
            tap(() => next(peerConnection.localDescription)),
            switchMap(() =>
              merge(
                peerConnection.trackSource.pipe(
                  map(val => val[0].streams[0]),
                  tap(stream => {
                    const video = this.$refs.video1;
                    video.srcObject = stream;
                    video.play();
                  }),
                ),
                source.pipe(
                  filter(val => val.params instanceof RTCSessionDescription),
                  tap(val => {
                    const desc = new RTCSessionDescription(val.params);
                    peerConnection.setRemoteDescription(desc);
                  }),
                ),
                peerConnection.candidateSource.pipe(
                  map(arr => arr[0]),
                  tap(event => next(event.candidate)),
                  switchMap(() => source),
                  filter(val => val.params instanceof RTCIceCandidate),
                  tap(val => {
                    const candidate = new RTCIceCandidate(val.params);
                    peerConnection.addIceCandidate(candidate);
                  }),
                ),
              ),
            ),
          );
        }),
      )
      .subscribe();
  },
};
</script>
<style lang="scss" scoped>
.caller {
  display: flex;
  flex-direction: column;
  padding: 20px;
  .videos {
    display: flex;
    .video {
      height: 200px;
      width: 400px;
    }
  }
}</style
>>
